package servlet;

import java.io.*;
import java.sql.*;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebInitParam;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import util.*;
import bll.*;
import model.*;
import dal.*;

/**
 * Servlet implementation class CompanyServlet
 */
@WebServlet(urlPatterns = { "/Project", "/project", "/ProjectServlet", "/projectServlet" }, initParams = { @WebInitParam(name = "mode", value = "") })
public class ProjectServlet extends HttpServlet {
	private static final long serialVersionUID = 1L;

	/**
	 * Default constructor.
	 */
	public ProjectServlet() {
		// TODO Auto-generated constructor stub
	}

	/**
	 * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse
	 *      response)
	 */
	protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {

		request.setCharacterEncoding("UTF-8");
		response.setContentType("text/xml; charset=UTF-8");

		String mode = request.getParameter("mode");

		if (mode.equalsIgnoreCase("new")) {

			if (RightUtil.<ProjectModel> checkInsertRight()) {

				// TODO : MORE CODE HERE

				getServletContext().getRequestDispatcher("/projectNew.jsp").forward(request, response);
			} else {
				// TODO no right
			}
		} else if (mode.equalsIgnoreCase("edit")) {

			ProjectModel query = new ProjectModel();
			String id = request.getParameter("id");
			query.setId(Integer.parseInt(id));

			GenericDal<ProjectModel, ProjectModelExt> dal = new GenericDal<ProjectModel, ProjectModelExt>(new ProjectModel());

			ProjectModel obj = null;
			try {
				obj = dal.select(query);
			} catch (SQLException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			} catch (ClassNotFoundException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			} catch (Exception e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}

			if (obj != null) {

				// TODO : MORE CODE HERE

				request.setAttribute("project", obj);
				getServletContext().getRequestDispatcher("/projectEdit.jsp").forward(request, response);

			} else {
				// TODO : data not found
			}
		} else if (mode.equalsIgnoreCase("view")) {

			ProjectModel query = new ProjectModel();
			String id = request.getParameter("id");
			query.setId(Integer.parseInt(id));

			GenericDal<ProjectModel, ProjectModelExt> dal = new GenericDal<ProjectModel, ProjectModelExt>(new ProjectModel());

			ProjectModel obj = null;
			try {
				obj = dal.select(query);
			} catch (SQLException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			} catch (ClassNotFoundException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			} catch (Exception e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}

			if (obj != null) {
				// TODO : LOAD MASTER DATA HERE
				// It's specific code that cannot be generated

				request.setAttribute("project", obj);
				getServletContext().getRequestDispatcher("/projectView.jsp").forward(request, response);

			} else {
				// TODO : data not found
			}
		} else if (mode.equalsIgnoreCase("quickInsert")) {
			response.setContentType("text/xml; charset=UTF-8");
			ProjectModel obj = new ProjectModel();

			// TODO set name here

			GenericDal<ProjectModel, ProjectModelExt> dal = new GenericDal<ProjectModel, ProjectModelExt>(new ProjectModel());

			int res = 0;
			try {
				String strName = request.getParameter("name");
				strName = new String(strName.getBytes("ISO-8859-1"), "UTF-8");

				obj.setName(strName);
				res = dal.insert(obj);
				PrintWriter out = response.getWriter();
				// TODO: check failed inserting case
				if (res > 0) {
					String resultXML = CommonUtil.createAjaxResultXML("project", "" + res);
					out.println(resultXML);
				}
				else
				{
					
				}
			} catch (ClassNotFoundException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			} catch (SQLException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			} catch (Exception e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}

			// TODO : return value

		} else if (mode.equalsIgnoreCase("delete")) {

			ProjectModel query = new ProjectModel();
			String id = request.getParameter("id");
			query.setId(Integer.parseInt(id));

			GenericDal<ProjectModel, ProjectModelExt> dal = new GenericDal<ProjectModel, ProjectModelExt>(new ProjectModel());

			int res = Integer.MIN_VALUE;
			try {
				res = dal.delete(query);
			} catch (SQLException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			} catch (ClassNotFoundException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			} catch (Exception e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}

			if (res == 0) {
				// TODO success
				// Redirect to somewhere
				response.sendRedirect("projectList.jsp");
				// getServletContext().getRequestDispatcher("/projectNew.jsp").forward(request,
				// response);
			} else {
				// TODO fail
				PrintWriter out = response.getWriter();
				out.println("Cannot delete!");
			}
		}
	}

	/**
	 * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse
	 *      response)
	 */
	protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {

		request.setCharacterEncoding("UTF-8");
		response.setContentType("text/html; charset=UTF-8");

		String mode = request.getParameter("mode");

		if (mode.equalsIgnoreCase("insert")) {

			ProjectModel obj = new ProjectModel();
			
			String avatar = request.getParameter("avatar");
			obj.setAvatar(avatar);
			//System.out.println(avatar);

			String name = request.getParameter("name");
			obj.setName(name);

			String code = request.getParameter("code");
			obj.setCode(code);

			String description = request.getParameter("description");
			obj.setDescription(description);

			// String id_type = request.getParameter("id_type");
			// if (id_type != null && !id_type.isEmpty()) {
			// obj.setIdType(Integer.parseInt(id_type));
			// }

			String pm = request.getParameter("pm");
			if (pm != null && !pm.isEmpty()) {
				obj.setPm(Integer.parseInt(pm));
			}

			String is_template = request.getParameter("is_template");

			obj.setIsTemplate(is_template != null && (is_template.equalsIgnoreCase("true") || is_template.equalsIgnoreCase("1")));

			String status = request.getParameter("status");
			if (status != null && !status.isEmpty()) {
				obj.setStatus(Integer.parseInt(status));
			}

			String plan_start_date_date = request.getParameter("plan_start_date_date");
			String plan_start_date_time = request.getParameter("plan_start_date_time");
			if (plan_start_date_date != null && !plan_start_date_date.isEmpty() && plan_start_date_time != null && !plan_start_date_time.isEmpty()) {
				obj.setPlanStartDate(DateTimeUtil.parseDateTime(plan_start_date_date, plan_start_date_time));
			} else {
				obj.setPlanStartDate(DateTimeUtil.parseDate(plan_start_date_date));
			}

			String plan_end_date_date = request.getParameter("plan_end_date_date");
			String plan_end_date_time = request.getParameter("plan_end_date_time");
			if (plan_end_date_date != null && !plan_end_date_date.isEmpty() && plan_end_date_time != null && !plan_end_date_time.isEmpty()) {
				obj.setPlanEndDate(DateTimeUtil.parseDateTime(plan_end_date_date, plan_end_date_time));
			} else {
				obj.setPlanEndDate(DateTimeUtil.parseDate(plan_end_date_date));
			}

			String real_start_date_date = request.getParameter("real_start_date_date");
			String real_start_date_time = request.getParameter("real_start_date_time");
			if (real_start_date_date != null && !real_start_date_date.isEmpty() && real_start_date_time != null && !real_start_date_time.isEmpty()) {
				obj.setRealStartDate(DateTimeUtil.parseDateTime(real_start_date_date, real_start_date_time));
			} else {
				obj.setRealStartDate(DateTimeUtil.parseDate(real_start_date_date));
			}

			String real_end_date_date = request.getParameter("real_end_date_date");
			String real_end_date_time = request.getParameter("real_end_date_time");
			if (real_end_date_date != null && !real_end_date_date.isEmpty() && real_end_date_time != null && !real_end_date_time.isEmpty()) {
				obj.setRealEndDate(DateTimeUtil.parseDateTime(real_end_date_date, real_end_date_time));
			} else {
				obj.setRealEndDate(DateTimeUtil.parseDate(real_end_date_date));
			}

			String id_company = request.getParameter("id_company");
			if (id_company != null && !id_company.isEmpty()) {
				obj.setIdCompany(Integer.parseInt(id_company));
			}

			// String event_date_date = request.getParameter("event_date_date");
			// String event_date_time = request.getParameter("event_date_time");
			// if (event_date_date != null && !event_date_date.isEmpty() &&
			// event_date_time != null && !event_date_time.isEmpty()) {
			// obj.setEventDate(DateTimeUtil.parseDateTime(event_date_date,
			// event_date_time));
			// } else {
			// obj.setEventDate(DateTimeUtil.parseDate(event_date_date));
			// }

			String attendees = request.getParameter("attendees");
			if (attendees != null && !attendees.isEmpty()) {
				obj.setAttendees(Integer.parseInt(attendees));
			}

			String id_venue = request.getParameter("id_venue");
			if (id_venue != null && !id_venue.isEmpty()) {
				obj.setIdVenue(Integer.parseInt(id_venue));
			}
			
			String budget = request.getParameter("budget");
            if (budget != null && !budget.isEmpty()) {
			    obj.setBudget(Double.parseDouble(budget));
            }

			obj.setCreator(SessionUtil.getCurrentUserID());

			if (CommonBll.checkInputs(obj)) {
				GenericDal<ProjectModel, ProjectModelExt> dal = new GenericDal<ProjectModel, ProjectModelExt>(new ProjectModel());

				int res = 0;
				try {
					res = dal.insert(obj);
				} catch (SQLException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				} catch (ClassNotFoundException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				} catch (Exception e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				}

				if (res > 0) {
					// TODO : success, redirect to somewhere
					response.sendRedirect("projectList.jsp");
					// getServletContext().getRequestDispatcher("/projectList.jsp").forward(request,
					// response);
				} else {
					// TODO : processing error here
				}
			} else {

				// invalid input

				request.setAttribute("project", obj);
				getServletContext().getRequestDispatcher("/projectInput.jsp").forward(request, response);

			}
		} else if (mode.equalsIgnoreCase("update")) {

			ProjectModel query = new ProjectModel();
			String id = request.getParameter("id");
			query.setId(Integer.parseInt(id));

			GenericDal<ProjectModel, ProjectModelExt> dal = new GenericDal<ProjectModel, ProjectModelExt>(new ProjectModel());

			ProjectModel obj = null;
			try {
				obj = dal.select(query);
			} catch (SQLException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			} catch (ClassNotFoundException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			} catch (Exception e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}

			if (obj != null) {

				//String avatar = request.getParameter("avatar");
				//obj.setAvatar(avatar);
				
				String name = request.getParameter("name");
				obj.setName(name);

				String code = request.getParameter("code");
				obj.setCode(code);

				String description = request.getParameter("description");
				obj.setDescription(description);

				// String id_type = request.getParameter("id_type");
				// obj.setIdType(Integer.parseInt(id_type));

				String pm = request.getParameter("pm");
				obj.setPm(Integer.parseInt(pm));

				String is_template = request.getParameter("is_template");
				obj.setIsTemplate(is_template != null && (is_template.equalsIgnoreCase("true") || is_template.equalsIgnoreCase("1")));

				String status = request.getParameter("status");
				obj.setStatus(Integer.parseInt(status));

				String plan_start_date_date = request.getParameter("plan_start_date_date");
				String plan_start_date_time = request.getParameter("plan_start_date_time");
				obj.setPlanStartDate(DateTimeUtil.parseDateTime(plan_start_date_date, plan_start_date_time));

				String plan_end_date_date = request.getParameter("plan_end_date_date");
				String plan_end_date_time = request.getParameter("plan_end_date_time");
				obj.setPlanEndDate(DateTimeUtil.parseDateTime(plan_end_date_date, plan_end_date_time));

				String real_start_date_date = request.getParameter("real_start_date_date");
				String real_start_date_time = request.getParameter("real_start_date_time");
				obj.setRealStartDate(DateTimeUtil.parseDateTime(real_start_date_date, real_start_date_time));

				String real_end_date_date = request.getParameter("real_end_date_date");
				String real_end_date_time = request.getParameter("real_end_date_time");
				obj.setRealEndDate(DateTimeUtil.parseDateTime(real_end_date_date, real_end_date_time));

				String id_company = request.getParameter("id_company");
				if (id_company != null && !id_company.isEmpty()) {
					obj.setIdCompany(Integer.parseInt(id_company));
				}

				// String event_date_date =
				// request.getParameter("event_date_date");
				// String event_date_time =
				// request.getParameter("event_date_time");
				// obj.setEventDate(DateTimeUtil.parseDateTime(event_date_date,
				// event_date_time));

				String attendees = request.getParameter("attendees");
				if (attendees != null && !attendees.isEmpty()) {
					obj.setAttendees(Integer.parseInt(attendees));
				} else {
					obj.setAttendees(Integer.MIN_VALUE);
				}

				String id_venue = request.getParameter("id_venue");
				if (id_venue != null && !id_venue.isEmpty()) {
					obj.setIdVenue(Integer.parseInt(id_venue));
				}
				
				String budget = request.getParameter("budget");
                if (budget != null && !budget.isEmpty()) {
				    obj.setBudget(Double.parseDouble(budget));
                }
				

				if (CommonBll.checkInputs(obj)) {

					int res = Integer.MIN_VALUE;
					try {
						res = dal.update(obj);
					} catch (SQLException e) {
						// TODO Auto-generated catch block
						e.printStackTrace();
					} catch (ClassNotFoundException e) {
						// TODO Auto-generated catch block
						e.printStackTrace();
					} catch (Exception e) {
						// TODO Auto-generated catch block
						e.printStackTrace();
					}

					if (res == 0) {
						// TODO success
						//Redirect
						response.sendRedirect("projectList.jsp");
					} else {
						// TODO error
					}
				} else {
					request.setAttribute("project", obj);
					getServletContext().getRequestDispatcher("/projectEdit.jsp").forward(request, response);
				}
			} else {
				// TODO data not found
			}
		} else if (mode.equalsIgnoreCase("quickInsert")) {
			ProjectModel obj = new ProjectModel();

			// TODO set name here

			GenericDal<ProjectModel, ProjectModelExt> dal = new GenericDal<ProjectModel, ProjectModelExt>(new ProjectModel());

			int res = 0;
			try {
				res = dal.insert(obj);
			} catch (ClassNotFoundException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			} catch (SQLException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			} catch (Exception e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}

			// TODO : return value

		}
	}
}